# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, api

import logging
_logger = logging.getLogger(__name__)

class IotDevice(models.Model):
    _inherit = "iot.device"

    def publish(self, method, **kwargs):
        self.ensure_one()
        self.gateway_id.publish(method, 'node', self.code, **kwargs)

    def action_put_config(self, value={}):
        self.ensure_one()
        values = {
            'name': self.name,
            'latitude': self.latitude,
            'longitude':self.longitude,
            'interval':self.interval,
            'router_code': self.router_code,
        }

        self.publish( 'put', values = values, userdata={'function': 'config'} )


    def action_del(self):
        self.ensure_one()
        self.publish( 'del', userdata={'function': 'del', 'router_code': self.router_code } )

    def action_get_config(self):
        self.ensure_one()
        self.publish( 'get', userdata={'function': 'config'} )


    @api.model
    def on_message_put(self, code, userdata=None, values=None, *args, **kwargs):
        print('on_message_put node: ', code, userdata, values, args, kwargs)
        if userdata.get( 'function' ) == 'values':
            print('on_message_put : values, node', values )
            sensors = values.get('sensors', [])
            self.env['iot.value'].update_values( sensors)


    @api.model
    def on_message_get_ack(self, code, userdata=None, result=None, *args, **kwargs):
        print('on_message_get_ack node: ', code, userdata, result, args, kwargs)
        if userdata.get( 'function' ) == 'config':
            print('on_message_get_ack : config, node', result )
            sensors = result.get('sensors', [])
            # 必须 有 gateway_id ??????
            obj = self.find_or_create({'code': code})
            obj.sensor_ids.update_sensors( obj, sensors)


    @api.model
    def on_message_put_ack(self, code, userdata=None, result=None, *args, **kwargs):
        print('on_message_put_ack node: ', code, userdata, result, args, kwargs)
        if userdata.get( 'function' ) == 'config':
            print('on_message_put_ack : config, node', result and 'ok' or 'error' )

    @api.model
    def on_message_del_ack(self, code, userdata=None, result=None, *args, **kwargs):
        print('on_message_del_ack node: ', code, userdata, result, args, kwargs)
        if userdata.get( 'function' ) == 'del':
            router_code = userdata.get( 'router_code' )
            print('on_message_del_ack : del ,  router remove node',  router_code, code , result and 'ok' or 'error' )

    def write(self, values):
        if 'gateway_id' in values.keys():
            gateway_id = values[ 'gateway_id']

            if self.gateway_id and self.gateway_id.id != gateway_id:
                self.action_del()
        
        return super(IotDevice, self).write(values)

